$(function () {
    obj.init();
});

var obj = new JsFun();
function JsFun() {
    return {
        form: null,
        imgArr:[],
        init: function () {
            this.form = new xhForm($('#xh_form'));
            this.form.parse().bindRequired($('#bt_modal_confirm',parent.document));
            $('#isBroken').select2({width: 200});
            this.listener();
        },
        listener: function () {
            var $this = this;
            //保存
            $('#bt_modal_confirm',parent.document).click(function () {
                $this.funObj().saveData();
            });
            //上传
            $('#image').on('change', function(){
                $this.funObj().uploadReport($(this));
            });

            //删除图片
            $('#imgFiles').on('click','.delBtn',function () {
                console.log('aaa');
                $this.funObj().delFiles($(this).attr('nodeId'));
            });
        },
        funObj: function () {
            var $this = this;
            return {
                uploadReport: function (dom) {
                    if (!dom.val()) {
                        window.top.xhTop.showError('错误','没有文件上传');
                        return false;
                    }
                    window.top.swal({
                        title: '上传中！请耐心等待...',
                        showConfirmButton: false,
                        type: 'success',
                        allowOutsideClick: false
                    });
                    var formData = new FormData();
                    var file = dom[0].files[0];
                    formData.append('file' , file);
                    $.ajax({
                        url:baseUrl + 'device/uploadImage',
                        method:'post',
                        dataType:'json',
                        data:formData,
                        processData:false,
                        contentType:false,
                        complete: function(XMLHttpRequest){
                            window.top.swal.close();
                            var result = XMLHttpRequest.responseJSON || XMLHttpRequest.responseText;
                            if(xhExtra.checkError(result)) return false;
                            $this.imgArr.push(result.msg);
                            xhFile.load($('#imgFiles ul'),$this.imgArr);
                        }
                    });
                    // $.ajaxFileUpload({
                    //     url: baseUrl + 'device/uploadImage',
                    //     secureuri:false,
                    //     fileElementId: dom[0].id,                               //file标签的id  
                    //     dataType: 'json',                                         //返回数据的类型  
                    //     success: function (data, status) {
                    //         if(data.error) {
                    //             window.top.xhTop.showMessage({
                    //                 title: data.error,
                    //                 type: 'error'
                    //             });
                    //             return false;
                    //         }
                    //         $this.imgArr.push(data.msg);
                    //         xhFile.load($('#imgFiles ul'),$this.imgArr);
                    //         // $('#image_url').val(data.msg);
                    //     },
                    //     error: function (data, status, e) {
                    //         window.top.xhTop.showMessage({
                    //             title: e,
                    //             type: 'error'
                    //         });
                    //     }
                    // });
                },
                saveData: function () {
                    var params = {device: device};
                    // params.push({id: id, text: name});

                    var abnormal = $('#isBroken').val();
                    var noteMag = $('#remarkContent').val();
                    // var imageUrl = $('#image_url').val();
                    if (!noteMag){
                        window.top.xhTop.showMessage({
                            title: '备注内容不能为空',
                            type: 'error'
                        });
                        xhExtra.setBtnNormal($('#bt_modal_confirm',parent.document));
                        return false;
                    }
                    if (abnormal === '1' && !$this.imgArr.length) {
                        window.top.xhTop.showMessage({
                            title: "此状态必须上传图片",
                            type: 'error'
                        });
                        xhExtra.setBtnNormal($('#bt_modal_confirm',parent.document));
                        return false;
                    }
                    params.abnormal = abnormal;
                    params.noteMag = noteMag;
                    params.imgArr = $this.imgArr;
                    var _prodData = $this.funObj().getDataTr();
                    if (_prodData === false) {
                        window.top.xhTop.showMessage({
                            title: '数量项需完整且正确填写',
                            type: 'error'
                        });
                        xhExtra.setBtnNormal($('#bt_modal_confirm',parent.document));
                        return false;
                    }
                    params.prodData = _prodData;
                    xhExtra.setBtnNormal($('#bt_modal_confirm',parent.document));
                    xhExtra.ajaxRequest('Device/addRegisterNote', params,
                        {success: true,check:false},function (res) {
                            if(res.code === 200) {
                                window.top.swal('成功',res.msg,'success');
                                window.top.xhTop.closeModal();
                                window.top.xhTop.getActiveFrame().obj.dataGrid.reload();
                            } else {
                                window.top.xhTop.showError(res.error);
                                xhExtra.setBtnNormal($('#bt_modal_confirm',parent.document));
                            }
                        });
                },
                getDataTr: function () {
                    var _arr = [];
                    var _check = false;
                    $('.num').each(function () {
                        var obj = {};
                        var dom = $(this);
                        obj.name = dom.attr('prodName');
                        obj.num = dom.val();
                        if (obj.num < 0 || obj.num === undefined || obj.num === '') {
                            _check = true;
                            return false;
                        }
                        var reg = /^\d+$/;//非负数
                        if (!reg.test(obj.num)) {
                            _check = true;
                            return false;
                        }
                        _arr.push(obj);
                    });
                    if (_check) {
                        return false;
                    } else {
                        return _arr;
                    }
                },
                delFiles:function (index) {
                    $this.imgArr = $this.imgArr.delete(index);
                    xhFile.load($('#imgFiles ul'),$this.imgArr);
                },
            }
        }
    }
}

Array.prototype.delete=function(delIndex){
    var temArray=[];
    for(var i=0;i<this.length;i++){
        if(i!=delIndex){
            temArray.push(this[i]);
        }
    }
    return temArray;
};

var xhFile = {
    load:function (dom,files) {
        if (!files) {
            return false;
        }
        if (!(files instanceof Array) ) { //判断是否是数组
            if (typeof(files) === 'string') {
                files = files.split(',');
            } else {
                window.top.xhTop.showError('错误', '传入未知文件类型');
                return false;
            }
        }
        var str = '';
        if (files.length > 0) {
            $.each(files,function (i,url) {
                str +=
                    '<li style="float: left;margin-right:5px; ">\n' +
                    '                                        <span>\n' +
                    '                                            <a target="_blank" href="'+url+'" title="'+url+'" href="" class="btn btn-default" style="text-align: center;border: 0px;">\n' +
                    '                                                <i class="fa fa-file-o fa-2x customer-size" aria-hidden="true"></i>\n' +
                    '                                                <br>\n' +
                    // '                                                <p style="text-align: center;margin-bottom: 0px;overflow: hidden;width: 30px;font-size: xx-small;">'+item['fileName']+'</p>\n' +
                    '                                            </a>\n' +
                    '                                            <br>\n' +
                    '                                            <a class="delBtn" nodeId="'+i+'" style="text-align: center;width: 60px;margin-bottom: 10px;display: block;cursor: pointer">删除</a>\n' +
                    '                                        </span>\n' +
                    '                                    </li>';
            });
        }
        dom.empty().append(str);
    }
};
